package com.sc.VenusQueryBeta.ui.fragments.login;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.hengjun.kingstar.sdk.widgets.CountDownButton;
import com.hengjun.kingstar.sdk.widgets.DeviceIDUtil;
import com.hengjun.kingstar.sdk.widgets.TipHelper;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.login.LoginContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.login.EquipmentLoginBean;
import com.sc.VenusQueryBeta.model.bean.login.FirstLoginSubmintBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.login.LoginPresenter;
import com.sc.VenusQueryBeta.ui.activites.country.CountryActivity;
import com.sc.VenusQueryBeta.ui.activites.login.FirstLoginActivity;
import com.sc.VenusQueryBeta.ui.activites.login.ForgotPasswordActivity;
import com.sc.VenusQueryBeta.ui.activites.login.RegisterActivity;
import com.sc.VenusQueryBeta.ui.fragments.vip.VipRootFragment;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by SC-02 on 2018/9/19.
 * 子LoginFragment
 * 1继承BaseMVPCompatFragment
 * 2必须实现契约类里面的view接口并且重写对应的方法（该fragment有请求就必须实现，重写，不然会报错）
 */

public class LoginFragment extends BaseMVPCompatFragment<LoginContract.LoginPresenter> implements LoginContract.ILoginView {
    @BindView(R.id.tv_country_code)
    TextView tvCountryCode;
    @BindView(R.id.phone_et)
    EditText phoneEt;
    @BindView(R.id.pwd_et)
    EditText pwdEt;
    @BindView(R.id.hide_et)
    ImageView hideEt;
    @BindView(R.id.imageView2)
    ImageView imageView2;
    @BindView(R.id.imageView3)
    ImageView imageView3;
    @BindView(R.id.tv_choose_country)
    TextView textView2;
    @BindView(R.id.country_name)
    TextView countryName;
    @BindView(R.id.fgt_pwd)
    TextView fgtPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.imageView)
    ImageView imageView1;
    @BindView(R.id.rl_click)
    RelativeLayout rlClick;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    boolean eyeOpen = false;
    private String countryCode = "0";//大陆
    private String deviceUid;
    private int sw;
    private Button btn_queding;
    private CountDownButton send;
    private EditText et_e;

    private PopupWindow popupWindow;
    private Toolbar toolbar;
    private PhoneNumberUtil phoneUtil;
    private Phonenumber.PhoneNumber parse;
    private String areaCode = "+86";
    private boolean isChoose = false;

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return LoginPresenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    public void initData() {
        super.initData();
        phoneUtil = PhoneNumberUtil.getInstance();
        deviceUid = new DeviceIDUtil(mActivity).getDeviceUuid().toString().replaceAll("-", "");
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        //初始化首次登陆发送验证码的按钮的
//        inputOtherPwdWindow();//打開首次驗證碼窗口
        hideEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (eyeOpen) {
                    //密码
                    pwdEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    eyeOpen = false;
                } else {
                    //明文
                    pwdEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    eyeOpen = true;
                }
            }
        });
    }

    @Override
    public boolean onBackPressedSupport() {
        mActivity.finish();
        return true;
    }

    /**
     * 提供实例化对象
     * @return 对象
     */
    public static LoginFragment newInstance() {
        return new LoginFragment();
    }

    @OnClick({R.id.rl_click, R.id.btn_login, R.id.btn_register, R.id.fgt_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_click://国家代码
                startActivityForResult(new Intent(getActivity(), CountryActivity.class), 12);
                break;
            case R.id.btn_login://登錄
                if (!phoneEt.getText().toString().trim().equals("") && !pwdEt.getText().toString().trim().equals("")) {
                    try {
                        LogUtils.e("sasa===121===" + tvCountryCode.getText().toString().substring(1));
                        parse = phoneUtil.parse(tvCountryCode.getText().toString() + phoneEt.getText().toString(), tvCountryCode.getText().toString().substring(1));
                        if (phoneUtil.isValidNumber(parse)) {
                            showProgressDialog("正在登陸.......");
                            if (countryCode.equals("1")) {//是澳门就不要 +53顛三倒四多65656
                                mPresenter.login(phoneEt.getText().toString(), pwdEt.getText().toString(), Constants.MEG, deviceUid, "");
                                LogUtils.e("是澳门就不要212 +53顛三倒四多65656");
                            } else {
                                LogUtils.e("是澳门就不要 +53顛三倒四多65656");
                                mPresenter.login(tvCountryCode.getText().toString() + phoneEt.getText().toString(), pwdEt.getText().toString(), Constants.MEG, deviceUid, "");
                            }
                        } else {
                            ToastUtils.showToast("手机号码不合法");
                        }
                    } catch (NumberParseException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtils.showToast("账号或密码不正确");
                }
                break;
            case R.id.btn_register:
                startNewActivity(RegisterActivity.class);
                break;
            case R.id.fgt_pwd:
                startNewActivity(ForgotPasswordActivity.class);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            Bundle bundle = data.getExtras();
            String countriesName = bundle.getString("countryName");
            LogUtil.e("countriesName========" + countriesName);
            String countryNumber = bundle.getString("countryNumber");
            LogUtil.e("countryNumber=======" + countryNumber);
            tvCountryCode.setText(countryNumber);
            countryName.setText(countriesName);
            if (countryNumber.equals("+86")) {
                countryCode = "0";
            } else if (countryNumber.equals("+853")) {
                countryCode = "1";
            } else if (countryNumber.equals("+852")) {
                countryCode = "2";
            } else if (countryNumber.equals("+886")) {
                countryCode = "3";
            } else if (countryNumber.equals("+")) {
                countryCode = "4";
            }
        } else {
            LogUtil.e("非100");
        }
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        LogUtils.e("onSupportVisible  loginfragment");
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.e("LoginFragment = onResume=");
        boolean out = SpUtils.getBoolean(MyApplication.app, Constants.OUT_DATE, false);
        if (!isChoose) {//是過期 設置之前的 並且不是跳轉到選擇的時候
            SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, false);
            String string = SpUtils.getString(MyApplication.app, Constants.PHONE, "");
            String areacode1 = SpUtils.getString(MyApplication.app, Constants.AREADECODE, "");
            isChoose = true;
            String areacode = SpUtils.getString(MyApplication.app, Constants.AREADECODE, areaCode);
            String phone = SpUtils.getString(MyApplication.app, Constants.PHONE, "");
            LogUtil.e("phone00=" + phone + "areacode00=" + areacode);
            LogUtil.e("string=" + string + "areacode=" + areacode1);
            if (areacode.equals("1")) {//澳門不用截取出來 因為根本沒傳過去
                tvCountryCode.setText("+853");
                countryCode = "1";
                countryName.setText(R.string.macao);
                phoneEt.setText(phone);
            } else {
                if (areacode.equals("3")) {
                    countryCode = "3";
                    tvCountryCode.setText("+886");
                    countryName.setText(R.string.taiwan);
                    String substring = phone.substring(4);
                    phoneEt.setText(substring);
                }
                if (areacode.equals("2")) {
                    countryCode = "2";
                    tvCountryCode.setText("+852");
                    countryName.setText(R.string.xianggang);
                    String substring = phone.substring(4);
                    phoneEt.setText(substring);
                }
                if (areacode.equals("0")) {
//                    ToastUtils.showToast(""+phone.substring(3));
                    String substring = phone.substring(3);
                    phoneEt.setText(substring);
                    countryCode = "0";
                    tvCountryCode.setText("+86");
                    countryName.setText(R.string.china);
                }
            }
        }

    }

    /**
     * 登录成功获得后台数据
     *
     * @param usersLoginBean
     */
    @Override
    public void showUsersLoginDataSuccess(UsersLoginBean usersLoginBean) {
        LogUtils.e("登录的参数" + usersLoginBean.getId() + "  " + usersLoginBean.getPassword() + "  " + usersLoginBean.getSmsCode() + "  " + usersLoginBean.getDeviceUID() + "  " + usersLoginBean.getToken() + "登陸碼" + usersLoginBean.getReturnCod());
        LogUtils.e("设备ID1=" + usersLoginBean.getDeviceUID());
        switch (usersLoginBean.getReturnCod()) {
            case 101:   //密碼錯誤
                ToastUtils.showToast("密碼錯誤");
                hideProgressDialog();////隱藏進度條
                break;
            case 102: //首次登錄獲取驗證碼
                hideProgressDialog();//隱藏進度條
                ToastUtils.showToast("首次登录");
                Intent intent = new Intent(mActivity, FirstLoginActivity.class);
                intent.putExtra(Constants.COUNTRY_CODE, countryCode);
                intent.putExtra(Constants.DIVICEUID, deviceUid);
                intent.putExtra(Constants.TVCOUNTRYCODE, tvCountryCode.getText().toString());
                intent.putExtra(Constants.PHONEET, phoneEt.getText().toString());
                intent.putExtra(Constants.PWD, pwdEt.getText().toString());
                startActivity(intent);
//                popupWindow.showAtLocation(rlRoot, Gravity.CENTER, 0, 0);
//                // 设置背景颜色变暗
//                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
//                lp.alpha = 0.5f;
//                mActivity.getWindow().setAttributes(lp);
                break;
            case 100: //登錄成功
                //保存登录时间
                SpUtils.putObject(MyApplication.app, usersLoginBean);//保存登陸數據
                SpUtils.putObject(MyApplication.getContext(), usersLoginBean);
                SpUtils.putString(MyApplication.app, Constants.USER, usersLoginBean.getId());
                hideProgressDialog();//隱藏進度條
//              startWithPop(VipRootFragment.newInstance());
//              startNewFragmentWithPop(VipRootFragment.newInstance());
                start(VipRootFragment.newInstance());
                SpUtils.putLong(MyApplication.app, Constants.LOGINTIME, System.currentTimeMillis() / 1000);
                SpUtils.putLong(MyApplication.app, Constants.LOGINTIMEOUT, System.currentTimeMillis() / 1000 + 12 * 60 * 60);//12*60*60    + 12 * 60 * 60)
                break;
            case 103: //賬號不存在
                ToastUtils.showToast("账号不存在");
                hideProgressDialog();//隱藏進度條
                break;
            default:   //讀不到指令
                hideProgressDialog();//隱藏進度條
                ToastUtils.showToast("读取不到指令");
                break;
        }

    }

    @Override
    public void showNetworkError() {
        hideProgressDialog();//隱藏進度條
    }

    /**
     * 第一次登获 设备 取验证码成功
     *
     * @param equipmentLoginBean
     */
    @Override
    public void showFirstBUserLoginCodeSuccess(EquipmentLoginBean equipmentLoginBean) {
        send.start();
        hideProgressDialog();
        SpUtils.putString(MyApplication.app, Constants.VERTIFICATION_CODE, equipmentLoginBean.getRandomNum());//保存驗證碼
        LogUtils.e("getRandomNum=" + equipmentLoginBean.getRandomNum());
        ToastUtils.showToast("" + equipmentLoginBean.getRandomNum());
        LogUtils.e("phone==" + equipmentLoginBean.getRegisterSmsnum());
        LogUtils.e("设备ID2" + equipmentLoginBean.getDeviceUID());
        // showUsersLoginDataSuccess(usersLoginBean.getReturnCod());
        LogUtils.e("第一次登录获取验证码" + equipmentLoginBean.getClientUID() + "  " + equipmentLoginBean.getDeviceUID() + "  " + equipmentLoginBean.getDeviceType() + "  " + equipmentLoginBean.getRegisterSmsnum() +
                "  " + equipmentLoginBean.getAreaCode());
    }

    /**
     * 首次登录输入验证码点击确认按钮成功得到后台数据
     *
     * @param firstLoginSubmintBean
     */
    @Override
    public void showFirstSumbitDataSuccess(FirstLoginSubmintBean firstLoginSubmintBean) {
        hideProgressDialog();
        LogUtils.e("getDeviceUID()==" + firstLoginSubmintBean.getDeviceUID() + "firstLoginSubmintBean.getReturnCod()=" + firstLoginSubmintBean.getReturnCod());
        LogUtils.e("第一次登录确认成功" + firstLoginSubmintBean.getId() + "  " + firstLoginSubmintBean.getSmsCode() + "  " + firstLoginSubmintBean.getPassword() + " " + firstLoginSubmintBean.getClientUID() +
                "  " + firstLoginSubmintBean.getDeviceUID() + "  " + firstLoginSubmintBean.getDeviceType());
        ToastUtils.showToast("已確認！");
        popupWindow.dismiss();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (send != null) {
            if (!send.isFinish()) {
                send.cancel();
            }
        }
    }

    /**
     * 首次登陸設備創窗口
     */
    private void inputOtherPwdWindow() {
        final View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_loigin, null);
        send = contentView.findViewById(R.id.btn_equipment);
        btn_queding = contentView.findViewById(R.id.btn_affirm);
        toolbar = contentView.findViewById(R.id.toolbar);
        et_e = contentView.findViewById(R.id.editText);

        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        }

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (send != null) {
                    if (!send.isFinish()) {
                        send.cancel();
                    }
                }
                et_e.setText("");
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1f;
                mActivity.getWindow().setAttributes(lp);
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (send != null) {
                        if (!send.isFinish()) {
                            send.cancel();
                        }
                    }
                    et_e.setText("");
                    popupWindow.dismiss();
                }
            });
        }
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (send.isFinish()) {//完成才調用
//                    if (et_e.getText().toString().trim().equals("")) {
                    showProgressDialog("正在發送");
                    if (countryCode.equals("1")) {
                        mPresenter.getFirstBUserLoginCode(phoneEt.getText().toString(), deviceUid, "android", phoneEt.getText().toString()); //flag=0/1 0就是第一次注册时传
                    } else {
                        mPresenter.getFirstBUserLoginCode(Constants.MEG + tvCountryCode.getText().toString() + phoneEt.getText().toString(), deviceUid, "android", tvCountryCode.getText().toString() + phoneEt.getText().toString()); //flag=0/1 0就是第一次注册时传
                    }
                } else {
                    ToastUtils.showToast("別著急哦");
                }
            }
        });

        //完成返回登錄界面  點擊確認按鈕
        btn_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                if (!et_e.getText().toString().trim().equals("")) {//
                    if (et_e.getText().toString().trim().equals(SpUtils.getString(mActivity, Constants.VERTIFICATION_CODE, ""))) {//驗證嗎一樣
                        if (countryCode.equals("1")) {
                            showProgressDialog("正在确认");
                            mPresenter.firstSumbit(phoneEt.getText().toString(), Constants.MEG, pwdEt.getText().toString(), Constants.MEG + phoneEt.getText().toString(), deviceUid, "android");
                        } else {
                            showProgressDialog("正在確認");
                            mPresenter.firstSumbit(tvCountryCode.getText().toString() + phoneEt.getText().toString(), Constants.MEG, pwdEt.getText().toString(), Constants.MEG + tvCountryCode.getText().toString() + phoneEt.getText().toString(), deviceUid, "android");
                        }
                    } else {
                        ToastUtils.showToast("验证码不一致");
                        showNetworkError();
                    }

                } else {
                    Animation shake = AnimationUtils.loadAnimation(mContext, R.anim.shake);//加载动画资源文件
                    et_e.startAnimation(shake);
                    TipHelper.Vibrate(mActivity, 100);
                    ToastUtils.showToast("驗證碼不能空！");
                }
            }
        });

    }

}
